import random
import time

import pytest
import requests
import json
from unittest.mock import patch, MagicMock

# 配置信息
API_URL = "https://cvm.tencentcloudapi.com/"
REGION = "ap-guangzhou"
SECRET_ID = "your-secret-id"  # 实际测试中应从环境变量获取
SECRET_KEY = "your-secret-key"  # 实际测试中应从环境变量获取


def generate_signature(params, secret_key):
    """生成签名（模拟实现）"""
    # 实际签名算法需要按照腾讯云API规范实现
    # 这里仅作模拟
    return "mock-signature"


def send_request(action, params):
    """发送API请求（模拟实现）"""
    common_params = {
        "Action": action,
        "Version": "2017-03-12",
        "Region": REGION,
        "SecretId": SECRET_ID,
        "Timestamp": int(time.time()),
        "Nonce": random.randint(1, 1000000),
        "SignatureMethod": "HmacSHA256"
    }
    all_params = {**common_params, **params}
    all_params["Signature"] = generate_signature(all_params, SECRET_KEY)

    response = requests.post(API_URL, data=all_params)
    return response.json()


class TestImportScheduledTask:
    @patch('requests.post')
    def test_import_task_success(self, mock_post):
        """测试成功导入定时任务"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "RequestId": "1234567890",
                "TaskId": "task-123456"
            }
        }
        mock_post.return_value = mock_response

        params = {
            "InstanceId": "ins-valid-id",
            "ScheduledAction": "StopInstances",
            "Time": "2025-06-01T02:00:00Z",
            "Recurrence": "Daily"
        }
        result = send_request("ImportScheduledTask", params)

        assert "Response" in result
        assert "TaskId" in result["Response"]

    @patch('requests.post')
    def test_import_task_invalid_instance(self, mock_post):
        """测试使用无效实例ID导入定时任务"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "InvalidInstanceId.NotFound",
                    "Message": "实例ID不存在"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        params = {
            "InstanceId": "ins-invalid-id",
            "ScheduledAction": "StopInstances",
            "Time": "2025-06-01T02:00:00Z",
            "Recurrence": "Daily"
        }
        result = send_request("ImportScheduledTask", params)

        assert "Response" in result
        assert "Error" in result["Response"]
        assert result["Response"]["Error"]["Code"] == "InvalidInstanceId.NotFound"

    @patch('requests.post')
    def test_import_task_missing_action(self, mock_post):
        """测试缺少ScheduledAction参数导入定时任务"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "MissingParameter.ScheduledAction",
                    "Message": "缺少必需参数ScheduledAction"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        params = {
            "InstanceId": "ins-valid-id",
            "Time": "2025-06-01T02:00:00Z",
            "Recurrence": "Daily"
        }
        result = send_request("ImportScheduledTask", params)

        assert "Response" in result
        assert "Error" in result["Response"]
        assert result["Response"]["Error"]["Code"] == "MissingParameter.ScheduledAction"

    @patch('requests.post')
    def test_import_task_invalid_action(self, mock_post):
        """测试使用无效ScheduledAction参数导入定时任务"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "InvalidParameterValue.ScheduledAction",
                    "Message": "ScheduledAction参数值无效"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        params = {
            "InstanceId": "ins-valid-id",
            "ScheduledAction": "InvalidAction",
            "Time": "2025-06-01T02:00:00Z",
            "Recurrence": "Daily"
        }
        result = send_request("ImportScheduledTask", params)

        assert "Response" in result
        assert "Error" in result["Response"]
        assert result["Response"]["Error"]["Code"] == "InvalidParameterValue.ScheduledAction"

    @patch('requests.post')
    def test_import_task_missing_time(self, mock_post):
        """测试缺少Time参数导入定时任务"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "MissingParameter.Time",
                    "Message": "缺少必需参数Time"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        params = {
            "InstanceId": "ins-valid-id",
            "ScheduledAction": "StopInstances",
            "Recurrence": "Daily"
        }
        result = send_request("ImportScheduledTask", params)

        assert "Response" in result
        assert "Error" in result["Response"]
        assert result["Response"]["Error"]["Code"] == "MissingParameter.Time"

    @patch('requests.post')
    def test_import_task_invalid_time_format(self, mock_post):
        """测试无效Time格式导入定时任务"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "InvalidParameterValue.Time",
                    "Message": "Time参数格式无效"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        params = {
            "InstanceId": "ins-valid-id",
            "ScheduledAction": "StopInstances",
            "Time": "2025-06-01 02:00:00",  # 缺少时区信息
            "Recurrence": "Daily"
        }
        result = send_request("ImportScheduledTask", params)

        assert "Response" in result
        assert "Error" in result["Response"]
        assert result["Response"]["Error"]["Code"] == "InvalidParameterValue.Time"

    @patch('requests.post')
    def test_import_task_past_time(self, mock_post):
        """测试使用过去时间导入定时任务"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "InvalidParameterValue.TimeInPast",
                    "Message": "Time参数值不能早于当前时间"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        params = {
            "InstanceId": "ins-valid-id",
            "ScheduledAction": "StopInstances",
            "Time": "2024-01-01T02:00:00Z",  # 过去的时间
            "Recurrence": "Daily"
        }
        result = send_request("ImportScheduledTask", params)

        assert "Response" in result
        assert "Error" in result["Response"]
        assert result["Response"]["Error"]["Code"] == "InvalidParameterValue.TimeInPast"

    @patch('requests.post')
    def test_import_task_invalid_recurrence(self, mock_post):
        """测试无效Recurrence参数导入定时任务"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "InvalidParameterValue.Recurrence",
                    "Message": "Recurrence参数值无效"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        params = {
            "InstanceId": "ins-valid-id",
            "ScheduledAction": "StopInstances",
            "Time": "2025-06-01T02:00:00Z",
            "Recurrence": "InvalidRecurrence"
        }
        result = send_request("ImportScheduledTask", params)

        assert "Response" in result
        assert "Error" in result["Response"]
        assert result["Response"]["Error"]["Code"] == "InvalidParameterValue.Recurrence"

    @patch('requests.post')
    def test_import_task_conflict(self, mock_post):
        """测试任务冲突情况下导入定时任务"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "Conflict.TaskConflict",
                    "Message": "导入的任务与现有任务冲突"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        params = {
            "InstanceId": "ins-valid-id",
            "ScheduledAction": "StopInstances",
            "Time": "2025-06-01T02:00:00Z",
            "Recurrence": "Daily"
        }
        result = send_request("ImportScheduledTask", params)

        assert "Response" in result
        assert "Error" in result["Response"]
        assert result["Response"]["Error"]["Code"] == "Conflict.TaskConflict"

    @patch('requests.post')
    def test_import_task_permission_denied(self, mock_post):
        """测试无权限导入定时任务"""
        mock_response = MagicMock()
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "AuthFailure.UnauthorizedOperation",
                    "Message": "无权限执行此操作"
                },
                "RequestId": "1234567890"
            }
        }
        mock_post.return_value = mock_response

        params = {
            "InstanceId": "ins-valid-id",
            "ScheduledAction": "StopInstances",
            "Time": "2025-06-01T02:00:00Z",
            "Recurrence": "Daily"
        }
        result = send_request("ImportScheduledTask", params)

        assert "Response" in result
        assert "Error" in result["Response"]
        assert result["Response"]["Error"]["Code"] == "AuthFailure.UnauthorizedOperation"


# 启动测试函数
def run_tests():
    pytest.main([__file__, "-v", "-s"])


if __name__ == "__main__":
    run_tests()    